﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using Lidgren.Network;

namespace GoodSyncGame_Server
{

    public enum Headers
    {
        NewData,
        SyncData
    }

    public class Player
    {
        public int Key { get; set; }
        public string Name { get; set; }
        public float posX { get; set; }

        public Player()
        {

        }
    }

    class Program
    {
        static NetServer Server;
        static Dictionary<int, Player> Players = new Dictionary<int, Player>();
        static NetDeliveryMethod DeliverType = NetDeliveryMethod.UnreliableSequenced;

        static int GenerateKey()
        {
            int key = 5000;
            Random rnd = new Random();

            do
            {
                key = rnd.Next(5000, 15000);

            } while (KeyUsed(key));

            return key;
        }

        static bool KeyUsed(int key)
        {
            foreach (KeyValuePair<int, Player> player in Players)
                if (player.Key == key) return true;

            return false;
        }

        static void Main(string[] args)
        {
            NetPeerConfiguration config = new NetPeerConfiguration("MyGame");
            config.Port = 7777;
            Server = new NetServer(config);
            new Thread(new ThreadStart(ReceiveData)).Start();
            Server.Start();
            Console.ReadKey();
        }

        static void BeginSendData(int playerkey, Headers header, out NetOutgoingMessage outmsg)
        {
            outmsg = Server.CreateMessage();
            outmsg.Write(playerkey);
            outmsg.Write((byte)header);
        }

        static void EndSendData(NetOutgoingMessage outmsg, NetConnection from = null, NetConnection to = null)
        {
            if (to == null)
            {
                //Send to everyone
                if (from != null)
                {
                    // Except the "from"
                    Server.SendToAll(outmsg, from, DeliverType, 0);
                }
                else
                {
                    // Includes the "from"
                    Server.SendToAll(outmsg, DeliverType);
                }
            }
            else
            {
                //Send to specific
                Server.SendMessage(outmsg, to, DeliverType);
            }
        }

        private static void ReceiveData()
        {
            NetIncomingMessage incmsg;
            NetOutgoingMessage outmsg;
            int playerkey;
            Player player;

            while (true)
            {
                if ((incmsg = Server.ReadMessage()) != null)
                {
                    switch (incmsg.MessageType)
                    {
                        case NetIncomingMessageType.StatusChanged:

                            NetConnectionStatus status = (NetConnectionStatus)incmsg.ReadByte();

                            if (status == NetConnectionStatus.Connected)
                            {
                                // Send the new player his data
                                player = new Player(); // New Player
                                player.Key = GenerateKey();
                                player.Name = "Player " + player.Key.ToString();
                                player.posX = 60.0f;
                                Players.Add(player.Key, player);
                                BeginSendData(player.Key, Headers.NewData, out outmsg);
                                outmsg.Write(Players.Count);

                                if (Players.Count <= 1)
                                {
                                    outmsg.WriteAllProperties(player);
                                }
                                else
                                {
                                    foreach (KeyValuePair<int, Player> otherplayer in Players)
                                        outmsg.WriteAllProperties(otherplayer.Value);
                                }

                                EndSendData(outmsg, null, incmsg.SenderConnection);
                                BeginSendData(player.Key, Headers.NewData, out outmsg);
                                outmsg.WriteAllProperties(player);
                                EndSendData(outmsg, incmsg.SenderConnection, null);
                            }

                            break;

                        case NetIncomingMessageType.Data:

                            playerkey = incmsg.ReadInt32();
                            Headers header = (Headers)incmsg.ReadByte();

                            if (header == Headers.SyncData)
                            {
                                float xPos = incmsg.ReadFloat();
                                Players[playerkey].posX += xPos;
                                BeginSendData(playerkey, Headers.SyncData, out outmsg);
                                outmsg.Write(xPos);
                                EndSendData(outmsg, incmsg.SenderConnection, null);
                            }

                            break;
                    }

                    Server.Recycle(incmsg);
                }
            }
        }
    }
}
